{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"Contains a variant of the densenet model definition.\"\"\"\n",
    "\n",
    "from __future__ import absolute_import\n",
    "from __future__ import division\n",
    "from __future__ import print_function\n",
    "\n",
    "import tensorflow as tf\n",
    "\n",
    "slim = tf.contrib.slim\n",
    "\n",
    "\n",
    "def trunc_normal(stddev): return tf.truncated_normal_initializer(stddev=stddev)\n",
    "\n",
    "\n",
    "def bn_act_conv_drp(current, num_outputs, kernel_size, scope='block'):\n",
    "    current = slim.batch_norm(current, scope=scope + '_bn')\n",
    "    current = tf.nn.relu(current)\n",
    "    current = slim.conv2d(current, num_outputs, kernel_size, scope=scope + '_conv')\n",
    "    current = slim.dropout(current, scope=scope + '_dropout')\n",
    "    return current\n",
    "\n",
    "def transition(net, num_outputs, scope='OK'):\n",
    "\tnet = bn_act_conv_drp(net, num_outputs, [1, 1], scope=scope + '_conv1x1')\n",
    "\tnet = slim.avg_pool2d(net, [2, 2], stride=2, scope=scope+'avgpool')\n",
    "\treturn net\n",
    "\n",
    "def block(net, layers, growth, scope='block'):\n",
    "    for idx in range(layers):\n",
    "        bottleneck = bn_act_conv_drp(net, 4 * growth, [1, 1],\n",
    "                                     scope=scope + '_conv1x1' + str(idx))\n",
    "        tmp = bn_act_conv_drp(bottleneck, growth, [3, 3],\n",
    "                              scope=scope + '_conv3x3' + str(idx))\n",
    "        net = tf.concat(axis=3, values=[net, tmp])\n",
    "    return net\n",
    "\n",
    "\n",
    "def densenet(images, num_classes=200, is_training=False,\n",
    "             dropout_keep_prob=0.8,\n",
    "             scope='densenet'):\n",
    "    \"\"\"Creates a variant of the densenet model.\n",
    "\n",
    "      images: A batch of `Tensors` of size [batch_size, height, width, channels].\n",
    "      num_classes: the number of classes in the dataset.\n",
    "      is_training: specifies whether or not we're currently training the model.\n",
    "        This variable will determine the behaviour of the dropout layer.\n",
    "      dropout_keep_prob: the percentage of activation values that are retained.\n",
    "      prediction_fn: a function to get predictions out of logits.\n",
    "      scope: Optional variable_scope.\n",
    "\n",
    "    Returns:\n",
    "      logits: the pre-softmax activations, a tensor of size\n",
    "        [batch_size, `num_classes`]\n",
    "      end_points: a dictionary from components of the network to the corresponding\n",
    "        activation.\n",
    "    \"\"\"\n",
    "    growth = 24\n",
    "    compression_rate = 0.5\n",
    "\n",
    "    def reduce_dim(input_feature):\n",
    "        return int(int(input_feature.shape[-1]) * compression_rate)\n",
    "\n",
    "    end_points = {}\n",
    "\n",
    "    with tf.variable_scope(scope, 'DenseNet', [images, num_classes]):\n",
    "        with slim.arg_scope(bn_drp_scope(is_training=is_training, keep_prob=dropout_keep_prob)) as ssc:\t\n",
    "            ##########################\n",
    "            # Put your code here.\n",
    "            scope = \"conv1\" \n",
    "            net = slim.conv2d(images, 2 * growth, [7, 7], stride=2, scope=scope)\n",
    "            end_points[scope] = net\n",
    "\n",
    "            scope=\"maxpool1\"\n",
    "            net = slim.max_pool2d(net, [2, 2], stride=2, scope=scope)\n",
    "            end_points[scope] = net\n",
    "\n",
    "            # block 1\n",
    "            scope = \"block1\"\n",
    "            net = block(net, 6, growth, scope=scope)\n",
    "            end_points[scope] = net\n",
    "          \n",
    "\n",
    "            # transition layer 1\n",
    "            scope = \"compress1\"\n",
    "            net = bn_act_conv_drp(net, reduce_dim(net), [1, 1], scope=scope)\n",
    "            end_points[scope] = net\n",
    "\n",
    "            scope = \"avgpool1\"\n",
    "            net = slim.avg_pool2d(net, [2, 2], stride = 2, scope=scope)\n",
    "            end_points[scope] = net\n",
    "            # block 2\n",
    "            scope = \"block2\"\n",
    "            net = block(net, 12, growth, scope=scope)\n",
    "            end_points[scope] = net             \n",
    "\n",
    "            # transition layer 2\n",
    "            scope = \"compress2\"\n",
    "            net = bn_act_conv_drp(net, reduce_dim(net), [1, 1], scope=scope)\n",
    "            end_points[scope] = net\n",
    "\n",
    "            scope = \"avgpool2\"\n",
    "            net = slim.avg_pool2d(net, [2, 2], stride = 2, scope=scope)\n",
    "            end_points[scope] = net\n",
    "\n",
    "            # block 3\n",
    "            scope = \"block3\"\n",
    "            net = block(net, 24, growth, scope=scope)\n",
    "            end_points[scope] = net\n",
    "            \n",
    "            # transition layer 3\n",
    "            scope = \"compress3\"\n",
    "            net = bn_act_conv_drp(net, reduce_dim(net), [1, 1], scope=scope)\n",
    "            end_points[scope] = net\n",
    "\n",
    "            scope = \"avgpool3\"\n",
    "            net = slim.avg_pool2d(net, [2, 2], stride = 2, scope=scope)\n",
    "            end_points[scope] = net\n",
    "\n",
    "            # block 4\n",
    "            scope = \"block4\"\n",
    "            net = block(net, 16, growth, scope=scope)\n",
    "            end_points[scope] = net\n",
    "\n",
    "            # classificatioin layer\n",
    "            scope = \"global_pool\"\n",
    "            net = slim.avg_pool2d(net, [7, 7], scope=scope) \n",
    "            end_points[scope] = net\n",
    "            scope = \"PreLogitsFlatten\"\n",
    "            net=slim.flatten(net, scope=scope)\n",
    "            end_points[scope] = net\n",
    "            scope = \"Logits\"\n",
    "            logits = end_points[scope]=slim.fully_connected(net, num_classes, activation_fn=None, scope=scope)\n",
    "            scope = \"Predictions\"\n",
    "            end_points[scope] = tf.nn.softmax(logits, name=scope)\n",
    "            ##########################\n",
    "    return logits, end_points\n",
    "\n",
    "\n",
    "def bn_drp_scope(is_training=True, keep_prob=0.8):\n",
    "    keep_prob = keep_prob if is_training else 1\n",
    "    with slim.arg_scope(\n",
    "        [slim.batch_norm],\n",
    "            scale=True, is_training=is_training, updates_collections=None):\n",
    "        with slim.arg_scope(\n",
    "            [slim.dropout],\n",
    "                is_training=is_training, keep_prob=keep_prob) as bsc:\n",
    "            return bsc\n",
    "\n",
    "\n",
    "def densenet_arg_scope(weight_decay=0.004):\n",
    "    \"\"\"Defines the default densenet argument scope.\n",
    "\n",
    "    Args:\n",
    "      weight_decay: The weight decay to use for regularizing the model.\n",
    "\n",
    "    Returns:\n",
    "      An `arg_scope` to use for the inception v3 model.\n",
    "    \"\"\"\n",
    "    with slim.arg_scope(\n",
    "        [slim.conv2d],\n",
    "        weights_initializer=tf.contrib.layers.variance_scaling_initializer(\n",
    "            factor=2.0, mode='FAN_IN', uniform=False),\n",
    "        activation_fn=None, biases_initializer=None, padding='same',\n",
    "            stride=1) as sc:\n",
    "        return sc\n",
    "\n",
    "\n",
    "densenet.default_image_size = 224\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Densenet的稠密连接提出是在Resnet的基础上的，Resnet的layer输入中加入了上一layer的输入，Densenet则将layer之前所有layer的输入全部进行处理后再输入本层，这样可以防止在网络深度加大以后导致的梯度消失，增强了特征的传递和再利用。\n",
    "### 我的理解是，传统串行的连接方式就好比是材料精炼的过程，提取特征的同时自然有物质的损失，但这些物质提早被筛除的物质不一定就是完全没用的，网络的输入端的网络层所筛掉的信息的再利用可以使特征的提取更完善。\n",
    "\n",
    "### GROWTH RATE反映了每层所保留的信息量的大小，传统网络的结构一般是输入层神经元数目最多，每层处理后递减，最后归纳出所需的特征。而由于Densenet在每层神经元处理后有稠密连接带来的feature map再利用，所以不必担心信息的损失比，可以将输出层数设得比较小，而且在这种情况下，也可以获得可观的结果，同时相对传统网络臃肿的输入端网络，参数数目可以降低很多，由此带来训练效率的提高。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
